package com.hangzhou.xyj.ui.activity;

import android.content.Intent;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.util.Pair;
import android.view.View;

import com.hangzhou.xyj.R;
import com.hangzhou.xyj.XYJApplication;
import com.hangzhou.xyj.db.GroupPushMsgDao;
import com.hangzhou.xyj.db.SimpleUserDao;
import com.hangzhou.xyj.event.NewMessageEvent;
import com.hangzhou.xyj.manager.IntentManager;
import com.hangzhou.xyj.manager.NotifyManager;
import com.hangzhou.xyj.model.GroupModel;
import com.hangzhou.xyj.model.GroupPushMsgModel;
import com.hangzhou.xyj.model.MessageModel;
import com.hangzhou.xyj.model.SimpleUserModel;
import com.hangzhou.xyj.model.UserModel;
import com.hangzhou.xyj.model.type.EGroupPushType;
import com.hangzhou.xyj.model.type.EMessageType;
import com.hangzhou.xyj.model.type.EMsgHandleResultType;
import com.hangzhou.xyj.model.type.EPushMessageType;
import com.hangzhou.xyj.net.handler.GetGroupsInfoHandler;
import com.hangzhou.xyj.net.handler.GetUsersInfoHandler;
import com.hangzhou.xyj.net.http.HttpLoader;
import com.hangzhou.xyj.net.request.GetGroupsInfoReq;
import com.hangzhou.xyj.net.request.GetUsersInfoReq;
import com.hangzhou.xyj.ui.activity.base.BaseActivity;
import com.hangzhou.xyj.ui.adapter.MyMessageAdapter;
import com.hangzhou.xyj.ui.widget.swipemenulistview.SwipeMenuRecyclerView;
import com.hangzhou.xyj.utils.EventBusUtil;
import com.hangzhou.xyj.utils.LogUtil;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.easeui.EaseConstant;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 我的消息页面
 */
public class MyMessageActivity extends BaseActivity {
    private final String TAG = getClass().getSimpleName();
    protected List<EMConversation> conversationList = new ArrayList<EMConversation>();
    private SwipeMenuRecyclerView mMessageRecyclerView;
    private MyMessageAdapter mMessageAdapter;
    private List<MessageModel> mMessageList = new ArrayList<>(); //绑定在Adapter上的数据模型
    private List<MessageModel> mGroupMsgList = new ArrayList<>(); //群组消息

    private List<MessageModel> mChatMsgList = new ArrayList<>(); //需要获取用户信息的单聊会话集合
    //环信数据库
    private SimpleUserDao mHXDao;

    @Override
    public void initTop() {
        enableTitle(true, "我的消息");
        EventBusUtil.register(this);
    }

//    @Override
//    protected void onNewIntent(Intent intent) {
//        super.onNewIntent(intent);
//        initIntentData(intent);
//    }

    @Override
    public void initIntentData(Intent intent) {
//        int pushType = intent.getIntExtra(DataKey.PUSH_TYPE, -1);
//        NotifyManager.getInstance().cancelMsg(mContext, EPushMessageType.valueOf(pushType));
//        switch (EPushMessageType.valueOf(pushType)) {
//            case SINGLE_CHAT:
//                NotifyManager.mSingleChatCount = 0;//重置
//                break;
//            case GROUP_CHAT:
//                NotifyManager.mGroupChatCount = 0;
//                break;
//            case ADD_GROUP:
//                NotifyManager.mAddGroupCount = 0;
//                break;
//            default:
//            case SYSTEM:
//                NotifyManager.mSystemCount = 0;
//                break;
//        }
    }

    @Override
    public void initLayouts() {
        setContentView(R.layout.activity_message);
    }

    @Override
    public void initViews() {
        mMessageRecyclerView = findView(R.id.rv_my_message);
        mMessageAdapter = new MyMessageAdapter(this, mMessageList);
        mMessageRecyclerView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        mMessageRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mMessageRecyclerView.setAdapter(mMessageAdapter);
    }

    @Override
    public void initDatas() {
        //清除通知栏
        NotifyManager.getInstance().cancelMsg(mContext, EPushMessageType.SINGLE_CHAT);
        NotifyManager.getInstance().cancelMsg(mContext, EPushMessageType.GROUP_CHAT);
        NotifyManager.getInstance().cancelMsg(mContext, EPushMessageType.ADD_GROUP);
        NotifyManager.getInstance().cancelMsg(mContext, EPushMessageType.SYSTEM);
        NotifyManager.mSingleChatCount = 0;//重置
        NotifyManager.mGroupChatCount = 0;
        NotifyManager.mAddGroupCount = 0;
        NotifyManager.mSystemCount = 0;
    }

    @Override
    public void initListeners() {
        mMessageAdapter.setOnRecyclerViewItemClickListener(new MyMessageAdapter.OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int viewType, int position) {
                MessageModel model = mMessageList.get(position);
                EMessageType messageType = EMessageType.valueOf(viewType);
                switch (messageType) {
                    case SYSTEM:
                        IntentManager.getInstance().goMySystemMessageActivity(mContext);
                        break;
                    case PERSON:
                        IntentManager.getInstance().goChatActivity(mContext, model.getUid(), EaseConstant.CHATTYPE_SINGLE);
                        break;
                    case GROUP:
                        IntentManager.getInstance().goChatActivity(mContext, model.getUid(), EaseConstant.CHATTYPE_GROUP);
                        break;
                    case NOTIFICATION:
                        IntentManager.getInstance().goMyOfficalMessageActivity(mContext);
                        break;
                    default:
                        break;
                }
            }

            /**
             * 删除会话
             *
             * @param view
             * @param position
             * @param list
             */
            @Override
            public void onDeleteViewClick(View view, int position, List<MessageModel> list) {
                if (position > mMessageList.size()) {
                    return;
                }
                EMClient.getInstance().chatManager().deleteConversation(mMessageList.get(position).getUid(), true);
                mMessageList.remove(position);
                mMessageAdapter.update(mMessageList);
            }
        });
    }

    /**
     * 加载数据
     */
    private void loadData() {
        //加载所有消息
        conversationList.clear();
        conversationList.addAll(loadConversationList());
        //清空消息
        mMessageList.clear();
        //环信用户本地数据库
        if (mHXDao == null) {
            mHXDao = new SimpleUserDao(mContext);
        }
        //加载系统消息
        loadMessage(EMessageType.SYSTEM);
        //加载个人消息
        loadMessage(EMessageType.PERSON);
        //加载群消息
        loadMessage(EMessageType.GROUP);
        //加载推送消息
        loadMessage(EMessageType.NOTIFICATION);

        //更新数据
        mMessageAdapter.update(mMessageList);
    }

    /**
     * 获取会话列表
     *
     * @return +
     */
    protected List<EMConversation> loadConversationList() {
        // 获取所有会话，包括陌生人
        Map<String, EMConversation> conversations = EMClient.getInstance().chatManager().getAllConversations();
        // 过滤掉messages size为0的conversation
        /**
         * 如果在排序过程中有新消息收到，lastMsgTime会发生变化
         * 影响排序过程，Collection.sort会产生异常
         * 保证Conversation在Sort过程中最后一条消息的时间不变
         * 避免并发问题
         */
        List<Pair<Long, EMConversation>> sortList = new ArrayList<Pair<Long, EMConversation>>();
        synchronized (conversations) {
            for (EMConversation conversation : conversations.values()) {
                if (conversation.getAllMessages().size() != 0) {
                    //if(conversation.getType() != EMConversationType.ChatRoom){
                    sortList.add(new Pair<Long, EMConversation>(conversation.getLastMessage().getMsgTime(), conversation));
                    //}
                }
            }
        }
        try {
            // Internal is TimSort algorithm, has bug
            sortConversationByLastChatTime(sortList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<EMConversation> list = new ArrayList<EMConversation>();
        for (Pair<Long, EMConversation> sortItem : sortList) {
            list.add(sortItem.second);
        }
        return list;
    }

    /**
     * 根据最后一条消息的时间排序
     */
    private void sortConversationByLastChatTime(List<Pair<Long, EMConversation>> conversationList) {
        Collections.sort(conversationList, new Comparator<Pair<Long, EMConversation>>() {
            @Override
            public int compare(final Pair<Long, EMConversation> con1, final Pair<Long, EMConversation> con2) {

                if (con1.first == con2.first) {
                    return 0;
                } else if (con2.first > con1.first) {
                    return 1;
                } else {
                    return -1;
                }
            }

        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadData();
    }

    /**
     * 加载消息
     *
     * @param type
     */
    private void loadMessage(EMessageType type) {
        switch (type) {
            case SYSTEM: //系统消息
                loadSystemMessage();
                break;
            case PERSON: //个人消息
                loadChatMessage();
                break;
            case GROUP: //群消息
                loadHXGroupMessage();
                break;
            case NOTIFICATION:
                loadNotificationMessage();
        }

    }

    /**
     * 加载推送的消息
     *
     * @param
     * @return
     * @author yaohuix
     * @date 2016/6/7 18:37
     */
    private void loadNotificationMessage() {
        GroupPushMsgDao dao = new GroupPushMsgDao(mContext);

        List<GroupPushMsgModel> allMsg = dao.getAllMessage("all");

        if (allMsg != null && allMsg.isEmpty()) {
            LogUtil.d(TAG, "group push msgs size 0");
            return;
        }
        LogUtil.d(TAG, "group push msg size:" + allMsg.size());
        //只要取第一条数据
        GroupPushMsgModel groupModel = allMsg.get(0);
        //准备一条消息
        MessageModel model = new MessageModel();
        model.setType(EMessageType.NOTIFICATION.getValue());
        model.setUid(groupModel.getToId());
        model.setTitle("戏友记官方");//标题
        model.setInsertTime(groupModel.getMsgTime());
        model.setContent(groupModel.getContent());
        mMessageList.add(model);
    }

    /**
     * 获取系统消息
     */
    private void loadSystemMessage() {
        GroupPushMsgDao dao = new GroupPushMsgDao(mContext);

        List<GroupPushMsgModel> allMsg = dao.getAllMessage(XYJApplication.getUserInfo().getUserId());

        int unReadCount = dao.getUnReadCount(XYJApplication.getUserInfo().getUserId());

        if (allMsg != null && allMsg.isEmpty()) {
            LogUtil.d(TAG, "group push msgs size 0");
            return;
        }
        LogUtil.d(TAG, "group push msg size:" + allMsg.size());

        //只要取第一条数据
        GroupPushMsgModel groupModel = allMsg.get(0);
        //准备一条消息
        MessageModel model = new MessageModel();
        model.setType(EMessageType.SYSTEM.getValue());
        model.setUid(groupModel.getToId());
        model.setTitle(groupModel.getGroupName());//标题
        model.setUnReadCount(unReadCount);
        model.setInsertTime(groupModel.getMsgTime());
        //消息处理结果
        EMsgHandleResultType resultType = EMsgHandleResultType.value(groupModel.getHandleResult());
        switch (resultType) {
            case AGREEED: //已同意
                model.setDesc(String.format("[%s]同意了%s的加入", groupModel.getGroupName(), groupModel.getPartUserName()));
                break;
            case REFUSEED: //已拒绝
                model.setDesc(String.format("[%s]拒绝了%s的加入", groupModel.getGroupName(), groupModel.getPartUserName()));
                break;
            default:
                switch (EGroupPushType.value(groupModel.getMsgType())) {
                    case ASK: //申请加群消息
                        model.setDesc(String.format("%s请求加入[%s]", groupModel.getPartUserName(), groupModel.getGroupName()));
                        break;
                    case AGREE: //同意加群消息
                        model.setDesc(String.format("[%s]同意您的加入", groupModel.getGroupName()));
                        break;
                    case REFUSE: //拒绝加群消息
                        model.setDesc(String.format("[%s]拒绝您的加入", groupModel.getGroupName()));
                        break;
                }
                break;
        }
        mMessageList.add(model);
        Log.d(TAG, "当前mMessageList的size" + mMessageList.size());
    }

    /**
     * 获取环信单聊消息
     */
    private void loadChatMessage() {
//        List<EMConversation> conversations = EMClient.getInstance().chatManager()
//                .getConversationsByType(EMConversation.EMConversationType.Chat);
        if (conversationList.size() <= 0) {
            return;
        }
        mChatMsgList.clear();
        //过滤出单聊消息
        LogUtil.d(TAG, "所有会话size ==" + conversationList.size());
        List<EMConversation> chatConversationList = new ArrayList<>();
        for (EMConversation conversation : conversationList) {
            if (conversation.getType() == EMConversation.EMConversationType.Chat) {
                LogUtil.d(TAG, "过滤到个人消息");
                chatConversationList.add(conversation);
            }
        }
        LogUtil.d(TAG, "个人会话size ==" + chatConversationList.size());

        MessageModel model;
        for (EMConversation conversation : chatConversationList) {
            //某个会话
            model = new MessageModel();
            model.setType(EMessageType.PERSON.getValue());
            model.setUid(conversation.conversationId());
            model.setTitle(conversation.getUserName());//标题
            model.setUnReadCount(conversation.getUnreadMsgCount());
            EMMessage lastMessage = conversation.getLastMessage();//最后一条信息
            if (lastMessage != null) {
                model.setEmMessage(lastMessage);
//                model.setDesc(lastMessage.getBody().toString());
                model.setInsertTime(lastMessage.getMsgTime());
            }

            SimpleUserModel hxUser = mHXDao.getUser(model.getUid());
            if (hxUser == null) { //代表本地数据库没有该用户信息，需要到服务器获取
                mChatMsgList.add(model);
            } else {
                model.setTitle(hxUser.getNickName());
                model.setImage(hxUser.getHeadPic());
                mMessageList.add(model);
            }
        }

        //需要去服务器获取的用户信息集合为空，说明本地数据库都有这些用户映射了，直接更新ui
        LogUtil.d(TAG, "单聊需要去服务器获取用户size ==" + mChatMsgList.size());
        if (mChatMsgList.isEmpty()) {
//            mMessageAdapter.update(mMessageList);
            return;
        }

        //去服务器获取批量用户详情信息
        List<String> ids = new ArrayList();
        for (int i = 0; i < mChatMsgList.size(); i++) {
            ids.add(mChatMsgList.get(i).getUid());
        }
        getUsersInfo(ids);
    }

    /**
     * 获取环信群组信息
     */
    private void loadHXGroupMessage() {
        //获取服务器的群组信息
        if (conversationList.size() <= 0) {
            return;
        }
        mGroupMsgList.clear();
        //过滤出群聊消息
        List<EMConversation> groupConversationList = new ArrayList<>();
        for (EMConversation conversation : conversationList) {
            if (conversation.getType() == EMConversation.EMConversationType.GroupChat) {
                groupConversationList.add(conversation);
            }
        }

        //群组id数组
        List<String> ids = new ArrayList<>();
        MessageModel msgModel;
        for (int i = 0; i < groupConversationList.size(); i++) {
            //某个会话
            EMConversation conversation = groupConversationList.get(i);
            //某个会话
            msgModel = new MessageModel();
            msgModel.setType(EMessageType.GROUP.getValue());
            msgModel.setUid(conversation.conversationId());
//                    EMConversation conversation = EMClient.getInstance().chatManager().getConversation(emGroup.getGroupId());
            if (conversation != null) {
                msgModel.setUnReadCount(conversation.getUnreadMsgCount());
                EMMessage lastMessage = conversation.getLastMessage();
                if (lastMessage != null) {
                    msgModel.setEmMessage(lastMessage);
//                    msgModel.setDesc(lastMessage.getBody().toString());
                    msgModel.setInsertTime(lastMessage.getMsgTime());
                }
            }

            mGroupMsgList.add(msgModel);

            ids.add(conversation.conversationId());
        }
        //批量获取群组详情
        getGroupDetail(ids);
    }

    /**
     * 获取群组信息
     */
    private void getGroupDetail(List<String> ids) {
        if (ids == null || ids.isEmpty()) {
            return;
        }

        //集合转成数组
        String[] groupIds = new String[ids.size()];
        groupIds = ids.toArray(groupIds);

        if (groupIds.length == 0) {
            return;
        }
        GetGroupsInfoReq req = new GetGroupsInfoReq(groupIds);
        HttpLoader.getInstance().sendRequest(new GetGroupsInfoHandler(req, new MyHttpResponseListener() {
            @Override
            public void onStart() {
            }

            @Override
            public void onSuccess(Object model) {
                super.onSuccess(model);
                if (model == null) return;
                List<GroupModel> groupModels = (List<GroupModel>) model;

                for (int i = 0; i < groupModels.size(); i++) {
                    GroupModel groupModel = groupModels.get(i);
                    //改变群组消息数据
                    //找到同一个组，设置数据
                    for (MessageModel msgModel : mGroupMsgList) {
                        if (msgModel.getUid().equals(groupModel.getGroupCode())) {
                            msgModel.setImage(groupModel.getGroupImage());
                            msgModel.setTitle(groupModel.getGroupName());//标题
                            msgModel.setUid(groupModel.getGroupCode());
                            mMessageList.add(msgModel);
                            break;
                        }
                    }
                }
                Log.d(TAG, "获取群聊之后的mMessageList的size = " + mMessageList.size());
                mMessageAdapter.update(mMessageList);
            }
        }, 0));
    }

    /**
     * 批量获取用户信息
     *
     * @param ids
     */
    private void getUsersInfo(List<String> ids) {
        if (ids == null || ids.isEmpty()) {
            return;
        }

        //集合转成数组
        String[] userIds = new String[ids.size()];
        userIds = ids.toArray(userIds);

        GetUsersInfoReq req = new GetUsersInfoReq(userIds);
        HttpLoader.getInstance().sendRequest(new GetUsersInfoHandler(req, new MyHttpResponseListener() {
            @Override
            public void onStart() {

            }

            @Override
            public void onSuccess(Object model) {
                List<UserModel> userModels = null;
                if (model != null) {
                    userModels = (List<UserModel>) model;
                }
                if (userModels != null && userModels.size() > 0) {
                    for (UserModel userModel : userModels) {
                        for (MessageModel msg : mChatMsgList) {
                            //用户id相同，代表同一个人
                            if (userModel.getUserId().equals(msg.getUid())) {
                                msg.setTitle(userModel.getNickName());
                                msg.setImage(userModel.getHeadPic());
                            }
                        }
                        //保存到本地环信用户数据库
                        SimpleUserModel hxUser = new SimpleUserModel();
                        hxUser.setUserId(userModel.getUserId());
                        hxUser.setNickName(userModel.getNickName());
                        hxUser.setHeadPic(userModel.getHeadPic());
                        mHXDao.addSimpleUser(hxUser);
                    }
                    //更新界面
                    mMessageList.addAll(mChatMsgList);
                    Log.d(TAG, "获取单聊列表之后的mMessageList的size = " + mMessageList.size());
                    mMessageAdapter.update(mMessageList);
                }
            }
        }, 0));
    }

    /**
     * 收到新消息事件，更新页面
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onNewMessageEvent(NewMessageEvent event) {
        LogUtil.d(TAG, "收到新消息");
        loadData();
    }

    /**
     * 根据消息类型删除信息
     *
     * @param msgType
     */
    private void removeByType(EMessageType msgType) {
        if (mMessageList == null) {
            return;
        }
        Iterator<MessageModel> iterator = mMessageList.iterator();
        while (iterator.hasNext()) {
            MessageModel model = iterator.next();
            if (model.getType() == msgType.getValue()) {
                iterator.remove();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBusUtil.unregister(this);
    }
}
